package cn.ailanyin.home.filters;

import cn.ailanyin.home.common.utils.JwtUtil;
import cn.ailanyin.home.common.utils.ResponseUtil;
import cn.ailanyin.home.module.login.properties.AuthConfigProperties;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证Token是否有效
 *
 * @author ailanyin
 * @date 2023-09-16 21:22:13
 */
@Component
@Order(1)
@RequiredArgsConstructor
public class JwtVerifyFilter implements Filter {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final AuthConfigProperties authConfigProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        // 白名单放行
        for (String whiteUri : authConfigProperties.getWhitelist()) {
            if (antPathMatcher.match(whiteUri, uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        // 获取Token
        String token = JwtUtil.getToken(request, true);
        // 验证Token
        if (StrUtil.isBlank(token) || !JwtUtil.verify(token)) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            ResponseUtil.errorAuth(response, HttpStatus.HTTP_UNAUTHORIZED, "暂无权限访问, 请重新登录");
            return;
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
